package goodbaby.dklt.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.classic.core.activity.BaseActivity;
import com.classic.core.activity.BaseActivityStack;
import com.classic.core.utils.StringUtil;
import com.classic.core.utils.ToastUtil;
import com.classic.okhttp.gbb.http.ActionHelp;
import com.classic.okhttp.gbb.http.ObjectCallback;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.tgd.gbb.uikit.ui.widget.asyncimageview.CircleImageView;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import goodbaby.dklt.GbbCache;
import goodbaby.dklt.GbbPreferences;
import goodbaby.dklt.R;
import goodbaby.dklt.bean.DeviceStudentInfo;
import goodbaby.dklt.bean.PowerBean;
import goodbaby.dklt.bluetoothutils.DeviceNumberUtils;
import goodbaby.dklt.bluetoothutils.UartService;

/**
 * Created by Jayden on 2016/4/23 18:50.
 *
 * @version V1.0
 * @Title: UserActivity
 * @Description: 个人中心页面
 */
public class UserActivity extends BaseActivity {

    private static final int REQUEST_ENABLE_BT = 2;
    public static TextView tvFindResult;
    public static TextView tvConnectDevice;
    private BaseActivityStack activityStack;
    private Intent bindIntent;
    private Button btnLoginOut;
    private String className;
    private ImageView ivBack;
    private CircleImageView ivHeadImg;
    private Handler mHandler;
    private Timer mTimer;
    private String macAddress;
    private String nickName;
    private String power;
    private RelativeLayout rlAbout;
    private RelativeLayout rlFindandUpdate;
    private RelativeLayout rlConnectDevice;
    private RelativeLayout rlSettingUserInfo;
    private String school;
    private TextView tvMacAddress;
    private TextView tvName;
    private TextView tvQty;
    private TextView tvSchoolandClass;
    private TextView tvTitle;
    private String userImgPath;

    private UartService mService = null;
    private BluetoothDevice mDevice = null;
    private BluetoothDevice maxDevice = null;
    private BluetoothAdapter mBtAdapter = null;
    private static final long SCAN_PERIOD = 10000; //10 seconds
    private int maxRssi = -1000;
    private int isFind = 0;
    private int isUploadData = 0;

    private byte[] currentData;
    private byte[] eleData;
    private byte[] sleepData;
    private byte[] stepData;

    private void clearUserInfo() {
        ActionHelp.userLoginOut(this, new ObjectCallback<String>() {

            public void onError(int paramAnonymousInt) {
            }

            public void onSuccess(String paramAnonymousString) {
                GbbCache.clear();
                Intent localIntent = new Intent(UserActivity.this, LoginActivity.class);
                startActivity(localIntent);
                activityStack.appExit(UserActivity.this);
                ToastUtil.showToast(UserActivity.this, "退出成功");
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }


    private void getQty() {
        ActionHelp.gbbSelectQty(this, new ObjectCallback<PowerBean>() {


            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(UserActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "失败:" + code);
                }
            }

            public void onSuccess(PowerBean paramAnonymousPowerBean) {
                power = paramAnonymousPowerBean.getPowerValue();
                setData();
            }

            @Override
            public Type getType() {
                return new TypeToken<PowerBean>() {
                }.getType();
            }
        });
    }


    private void setData() {
        Picasso.with(this).load(userImgPath).into(ivHeadImg);
        tvName.setText(nickName);
        if (!StringUtil.isEmpty(className)) {
            tvSchoolandClass.setText(school + "\b\b" + className);
        } else {
            tvSchoolandClass.setText(school);
        }
        tvMacAddress.setText(macAddress);
        tvQty.setText(power + "%");
    }


    public int getLayoutResId() {
        return R.layout.activity_user;
    }

    public byte[] getShockValue() {
        StringBuffer localStringBuffer = new StringBuffer();
        localStringBuffer.append("ab").append("00000500000000").append("01").append("00080000");
        return StringUtil.HexString2Bytes(localStringBuffer.toString());
    }

    public void initData() {
        super.initData();
        activityStack = BaseActivityStack.getInstance();
        mTimer = new Timer();
        service_init();
        mHandler = new Handler();
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBtAdapter = bluetoothManager.getAdapter();
        if (!this.mBtAdapter.isEnabled()) {
            Intent localIntent = new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE");
            Log.v("BluetoothAdapter", "BluetoothAdapter.ACTION_REQUEST_ENABLE");
            startActivityForResult(localIntent, 2);
        }
        if (this.mBtAdapter == null) {
            ToastUtil.showToast(this, "蓝牙不可用");
            finish();
            return;
        }
        userImgPath = GbbPreferences.getHeadImg();
        nickName = GbbPreferences.getName();
        school = GbbPreferences.getSchoolName();
        className = GbbPreferences.getClassName();
        macAddress = GbbPreferences.getBraceletAddress();
    }

    public void initView() {
        super.initView();
        tvTitle = (TextView) findViewById(R.id.tv_common_title);
        tvTitle.setText("个人中心");
        ivBack = (ImageView) findViewById(R.id.iv_common_back);
        ivBack.setVisibility(View.VISIBLE);
        ivBack.setOnClickListener(this);
        rlAbout = (RelativeLayout) findViewById(R.id.rl_about);
        rlAbout.setOnClickListener(this);
        rlFindandUpdate = (RelativeLayout) findViewById(R.id.rl_findandupdate);
        rlFindandUpdate.setOnClickListener(this);
        rlConnectDevice = (RelativeLayout) findViewById(R.id.rl_connect_device);
        rlConnectDevice.setOnClickListener(this);
        rlSettingUserInfo = (RelativeLayout) findViewById(R.id.rl_setting_userinfo);
        rlSettingUserInfo.setOnClickListener(this);
        btnLoginOut = (Button) findViewById(R.id.btn_loginout);
        btnLoginOut.setOnClickListener(this);
        ivHeadImg = (CircleImageView) findViewById(R.id.iv_user_headimg);
        tvName = (TextView) findViewById(R.id.tv_user_name);
        tvSchoolandClass = (TextView) findViewById(R.id.tv_schoolandclass);
        tvQty = (TextView) findViewById(R.id.tv_qty);
        tvMacAddress = (TextView) findViewById(R.id.tv_macaddress);
        tvFindResult = (TextView) findViewById(R.id.tv_find_result);
        tvConnectDevice = (TextView) findViewById(R.id.tv_connect_device);
        getQty();
        setData();
    }

    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
    }

    protected void onDestroy() {
        super.onDestroy();
        GbbCache.clearData();
        try {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
            unbindService(mServiceConnection);
            mService.stopSelf();
            mService = null;
            if (isUploadData == 1) {
                mBtAdapter.stopLeScan(mLeScanCallback);
            } else {
                mBtAdapter.stopLeScan(mLeScanCallback2);
            }
            return;
        } catch (Exception localException) {
            Log.e("", localException.toString());
        }
    }

    protected void onResume() {
        super.onResume();
        userImgPath = GbbPreferences.getHeadImg();
        nickName = GbbPreferences.getName();
        macAddress = GbbPreferences.getBraceletAddress();
        setData();
    }

    public void viewClick(View paramView) {
        super.viewClick(paramView);
        switch (paramView.getId()) {
            default:
                break;
            case R.id.iv_common_back:
                finish();
                break;
            case R.id.rl_about:
                startActivity(new Intent(this, AboutActivity.class));
                break;
            case R.id.rl_setting_userinfo:
                startActivity(new Intent(this, UserInfoActivity.class));
                break;
            case R.id.rl_findandupdate:
                mService.disconnect();
                tvFindResult.setText("开始查找");
                maxDevice = null;
                maxRssi = -1000;
                isUploadData = 0;
                scanLeDevice(true);
                rlFindandUpdate.setEnabled(false);
                rlConnectDevice.setEnabled(false);
                break;
            case R.id.rl_connect_device:
                if (StringUtil.isEmpty(macAddress)) {
                    ToastUtil.showToast(activity,"请先绑定手环");
                } else {
                    mService.disconnect();
                    isUploadData = 1;
                    tvConnectDevice.setText("开始连接");
                    scanLeDevice(true);
                    rlFindandUpdate.setEnabled(false);
                    rlConnectDevice.setEnabled(false);
                }
                break;
            case R.id.btn_loginout:
                clearUserInfo();
                break;
        }
    }

    private void service_init() {
        bindIntent = new Intent(UserActivity.this, UartService.class);
        bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        // registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
        LocalBroadcastManager.getInstance(UserActivity.this).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
        intentFilter.addAction(UartService.RSSI_DATA);

        return intentFilter;
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mService = ((UartService.LocalBinder) rawBinder).getService();
            Log.d("", "onServiceConnected mService= " + mService);
            if (!mService.initialize()) {
                Log.e("", "Unable to initialize Bluetooth");
                finish();
            }

        }

        public void onServiceDisconnected(ComponentName classname) {
            ////     mService.disconnect(mDevice);
            mService = null;
        }
    };

    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {

        private Handler myHandler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (mService != null) {
                    mService.getRssi();
                }
                myHandler.postDelayed(this, 200);
            }
        };

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (!action.equals(UartService.RSSI_DATA))
                Log.d("Uart", "recv action=" + action);

            final Intent mIntent = intent;
            //*********************//
            if (action.equals(UartService.ACTION_GATT_CONNECTED)) {

                myHandler.postDelayed(runnable, 200);
                setTimerTask();
                if (isUploadData == 1) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvConnectDevice.setText("连接成功");
                        }
                    });
                }
            }

            //*********************//
            else if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
                rlFindandUpdate.setEnabled(true);
                rlConnectDevice.setEnabled(true);
                myHandler.removeCallbacks(runnable);
                runOnUiThread(new Runnable() {
                    public void run() {
                        mService.close();
                    }
                });
            } else if (action.equals(UartService.RSSI_DATA)) {
                //Log.v("myrssi", "mainactivity get rssi");
                final String myrssi = intent.getStringExtra(UartService.EXTRA_DATA);
                Log.e("myrssi", myrssi);
                //rssiMessage.setText("RSSI: "+myrssi);
                int rssi = Integer.parseInt(myrssi);
                if (rssi < -100) {
                    Toast.makeText(context, "距离有点远噢", Toast.LENGTH_SHORT).show();
                    myHandler.removeCallbacks(runnable);
                }
                rlFindandUpdate.setEnabled(true);
                rlConnectDevice.setEnabled(true);
            }

            //*********************//
            else if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
                mService.enableTXNotification();
            }
            //*********************//

            else if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {


                byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
                if (txValue == null) return;
                if (isUploadData == 1) {
                    if (currentData != null) {
                        if (currentData.length < 300) {
                            SyncCache(txValue);
                        }
                    } else {
                        SyncCache(txValue);
                    }
                }
//                SyncCache(txValue);
//                String eleInfo = StringUtil.Bytes2HexString(txValue);
//                Log.e("aaaaa", eleInfo);

            }
            //*********************//
            else if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
                //showMessage("Device doesn't support UART. Disconnecting");
                mService.disconnect();
            }


        }
    };

    private void SyncCache(byte[] txValue) {
        byte[] data = GbbCache.getBleData();
        if (data != null) {
            currentData = new byte[txValue.length + data.length];
            System.arraycopy(data, 0, currentData, 0, data.length);
            System.arraycopy(txValue, 0, currentData, data.length, txValue.length);
            GbbCache.setBleData(currentData);
        } else {
            currentData = new byte[txValue.length];
            currentData = txValue;
            GbbCache.setBleData(currentData);
        }
        if (currentData.length > 300) {
            Log.e("temp", Arrays.toString(currentData));
            Log.e("temp", currentData.length + "");
            GbbCache.clearData();
            syncData();
        }
//        Log.e("bledata", StringUtil.Bytes2HexStringNoX(currentData));
//        Log.e("bledata", currentData.length + "");
//        Log.e("bledata", StringUtil.Bytes2HexStringNoX(currentData).length() + "");
//        Log.e("oneData", String.valueOf(currentData[13]) + "----" + String.valueOf(currentData[12]) + "----" + String.valueOf(currentData[11]) + "----" + String.valueOf(currentData[10])+ "----" + String.valueOf(currentData[9]));

    }

    private void syncData() {
        byte[] tempByte;
        for (int i = 1; i < currentData.length; i++) {
            if (currentData[i] == -85) {
                tempByte = new byte[i];
                for (int j = 0; j < i; j++) {
                    tempByte[j] = currentData[j];
                }
                if (tempByte[10] == 1) {
                    if (eleData == null) {
                        eleData = tempByte;
                        tempByte = new byte[400];
                    }
                } else if (tempByte[10] == 2) {
                    if (stepData == null) {
                        stepData = tempByte;
                        tempByte = new byte[400];
                    }
                } else if (tempByte[10] == 3) {
                    if (sleepData == null) {
                        sleepData = tempByte;
                        tempByte = new byte[400];
                    }
                } else if (tempByte[10] == 4) {
                    break;
                }
                for (int t = 0; t < currentData.length - i; t++) {
                    tempByte[t] = currentData[t + i];
                }
                currentData = new byte[400];
                currentData = tempByte;
                i = 1;
            }
        }
        int stepNum = 0;
        int eleNum = 0;
        String deepTime;
        String lightTime;
        String startTime;
        String endTime;
        if (stepData != null) {
            stepNum = DeviceNumberUtils.stepNumber(stepData);
        } else {
            stepNum = 0;
        }
        if (eleData != null) {
            eleNum = DeviceNumberUtils.eleNum(eleData);
        } else {
            eleNum = 0;
        }
        if (sleepData != null) {
            DeviceNumberUtils.setSleepInfo(sleepData);
            deepTime = GbbPreferences.getDeepSleep();
            lightTime = GbbPreferences.getLightSleep();
            startTime = GbbPreferences.getStartTime();
            endTime = GbbPreferences.getEndTime();
        } else {
            deepTime = "0";
            lightTime = "0";
            startTime = "";
            endTime = "";
        }
        Log.e("temp", Arrays.toString(eleData));
        Log.e("temp", Arrays.toString(stepData));
        Log.e("temp", Arrays.toString(sleepData));
        Log.e("temp", stepNum + "");
        Log.e("temp", eleNum + "");

        uploadDeviceData(startTime, endTime, deepTime, lightTime, stepNum + "", eleNum + "");
    }

    private void uploadDeviceData(String startTime, String endTime, String deepSleep, String lightSleep, String stepNum, String powerValue) {
        ActionHelp.gbbUploadDeviceData(activity, macAddress, startTime, endTime, deepSleep, lightSleep, stepNum, powerValue, new ObjectCallback<String>() {
            @Override
            public void onSuccess(String response) {
                ToastUtil.showToast(activity, "数据同步成功");
            }

            @Override
            public void onError(int code) {
                if (code == 301) {
                    Intent intent = new Intent(UserActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(UserActivity.this, "数据同步失败");
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<String>() {
                }.getType();
            }
        });
    }

    private void setTimerTask() {
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                findDevice();
            }
        }, 2000);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isUploadData == 1) {
                        mBtAdapter.stopLeScan(mLeScanCallback);
                        if (isFind == 1) {
                            mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(StringUtil.getBlueToothMacAddress(macAddress));
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mService.connect(StringUtil.getBlueToothMacAddress(macAddress));
                                }
                            }, 500);
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvConnectDevice.setText("没有找到设备");
                                    rlFindandUpdate.setEnabled(true);
                                    rlConnectDevice.setEnabled(true);
                                }
                            });
                        }
                    } else {
                        mBtAdapter.stopLeScan(mLeScanCallback2);
                        if (maxDevice != null) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(maxDevice.getAddress());
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            mService.connect(maxDevice.getAddress());
                                        }
                                    }, 500);

                                }
                            });
                            getBabyMessage(maxDevice.getAddress());
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tvFindResult.setText("没有找到设备");
                                    rlFindandUpdate.setEnabled(true);
                                    rlConnectDevice.setEnabled(true);
                                }
                            });
                        }
                    }


                    Log.v("bletooth", "mBluetoothAdapter.stopLeScan");
                }
            }, SCAN_PERIOD);

            if (isUploadData == 1) {
                mBtAdapter.startLeScan(mLeScanCallback);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvConnectDevice.setText("正在查找");
                    }
                });
            } else {
                mBtAdapter.startLeScan(mLeScanCallback2);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvFindResult.setText("正在查找");
                    }
                });
            }
            Log.v("bletooth", "mBluetoothAdapter.startLeScan");
        } else {
            if (isUploadData == 1) {
                mBtAdapter.stopLeScan(mLeScanCallback);
            } else {
                mBtAdapter.stopLeScan(mLeScanCallback2);
            }
        }

    }

    private void getBabyMessage(String address) {
        ActionHelp.gbbGetBabyNameByMacAddress(activity, StringUtil.getServiceBlueToothMacAddress(address), new ObjectCallback<DeviceStudentInfo>() {
            @Override
            public void onError(int code) {
                rlFindandUpdate.setEnabled(true);
                rlConnectDevice.setEnabled(true);
                if (code == 301) {
                    Intent intent = new Intent(UserActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast(activity, "请求错误");
                }
            }

            @Override
            public void onSuccess(DeviceStudentInfo response) {
                if (StringUtil.isEmpty(response.getName())) {
                    tvFindResult.setText("该手环没有绑定学生");
                } else {
                    tvFindResult.setText(response.getName());
                }
                rlFindandUpdate.setEnabled(true);
                rlConnectDevice.setEnabled(true);
            }

            @Override
            public Type getType() {
                return new TypeToken<DeviceStudentInfo>() {
                }.getType();
            }
        });
    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    if (device.getAddress().equals(StringUtil.getBlueToothMacAddress(macAddress))) {
                        isFind = 1;
                    }
                }
            };

    private BluetoothAdapter.LeScanCallback mLeScanCallback2 =
            new BluetoothAdapter.LeScanCallback() {

                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    if (rssi > maxRssi) {
                        maxRssi = rssi;
                        maxDevice = device;
                    }
                }
            };

    private void findDevice() {
        if (mDevice == null) {
            rlFindandUpdate.setEnabled(true);
            rlConnectDevice.setEnabled(true);
            Toast.makeText(UserActivity.this, "请先配对设备", Toast.LENGTH_SHORT).show();
            return;
        }
        mService.writeRXCharacteristic(getShockValue());
//        runOnUiThread(new Runnable() {
//            public void run() {
//                tvFindResult.setText("找到设备");
//            }
//        });
    }

}
